package com.zonski.jbots.game.resources;

import com.zonski.jbots.engine.UsableResource;
import com.zonski.jbots.engine.Engine;
import com.zonski.jbots.engine.Entity;
import com.zonski.jbots.game.EntityHelper;

public abstract class IntermittentResource extends UsableResource
{
    private int lastCreationTime;
    private int updatesBetweenCreations;
    private boolean killOwner;

    public IntermittentResource(int updatesBetweenCreations)
    {
        this.lastCreationTime = -updatesBetweenCreations;
        this.updatesBetweenCreations = updatesBetweenCreations;
    }

    /**
     * Indicates whether the resource can suck the owners battery completely dry
     * @return whether or not the resource can kill its owner
     */
    public boolean getKillOwner()
    {
        return this.killOwner;
    }

    /**
     * Indicates whether the resource can suck the owners battery completely dry
     * @param killOwner kill the owner or not
     */
    public void setKillOwner(boolean killOwner)
    {
        this.killOwner = killOwner;
    }


    public int getUpdatesBetweenCreations()
    {
        return this.updatesBetweenCreations;
    }

    public void setUpdatesBetweenCreations(int updatesBetweenCreations)
    {
        this.updatesBetweenCreations = updatesBetweenCreations;
    }

    public void update(Engine engine)
        throws Exception
    {
        if(isBeingUsed() && (this.lastCreationTime + this.updatesBetweenCreations) < engine.getUpdates())
        {
            int currentCost = this.getCurrentChargeCost();
            int charge = EntityHelper.getCharge(this.getOwner());
            if(currentCost < charge || killOwner)
            {
                Entity entity = create(engine);
                if(entity != null)
                {
                    EntityHelper.addCharge(this.getOwner(), -currentCost, false);
                    EntityHelper.addCharge(entity, currentCost, true);
                    engine.addEntity(entity);
                    this.lastCreationTime = engine.getUpdates();
                }
            }
        }
        super.update(engine);
    }

    /**
     * Obtains the current charge cost, this value will be transfered to
     * the object created. If the owner doesn't have enough power, the
     * object doesn't get created
     * @return the charge for creating the object
     */
    public abstract int getCurrentChargeCost();


    /**
     * Creates the entity for this resource or returns null if
     * the entity cannot be created 
     */
    protected abstract Entity create(Engine engine)
        throws Exception;
}
